<template>
    <div class="app-container">
        <!-- 顶部操作区域 -->
        <el-card class="box-card no-border-card" shadow="never">
            <div class="header-buttons">
                <el-button type="primary" icon="Plus" @click="handleAdd" plain>新增</el-button>
                <el-button type="success" icon="Edit" @click="handleEdit" :disabled="selectedPendingRows.length !== 1"
                    plain>修改</el-button>
                <el-button type="danger" icon="Delete" :disabled="selectedPendingRows.length === 0" plain>删除</el-button>
                <el-button type="warning" icon="Download" @click="handleExport" plain>导出</el-button>
                <div class="right-search">

                    <el-tooltip class="box-item" effect="dark" content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle />
                    </el-tooltip>
                    <el-tooltip class="box-item" effect="dark" content="刷新" placement="top">
                        <el-button :icon="Refresh" circle />
                    </el-tooltip>
                </div>
            </div>
        </el-card>

        <!-- 待处理任务列表 -->
        <el-card class="box-card" shadow="never" style="margin-top: 20px;">
            <template #header>
                <div class="card-header">
                    <span>待处理任务列表</span>
                </div>
            </template>
            <!-- 表格内容将在这里 -->
            <el-table :data="pendingTasks" style="width: 100%" @selection-change="handlePendingSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="客户姓名" />
                <el-table-column prop="phone" label="手机号码" />
                <el-table-column prop="channelName" label="渠道名称" />
                <el-table-column prop="activityName" label="活动名称" />
                <el-table-column prop="courseName" label="课程名称" />
                <el-table-column prop="contractPrice" label="合同金额" />
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button type="text" icon="View" @click="handleView(scope.row)">查看</el-button>
                        <el-button type="text" icon="Document">预览</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination :current-page="pendingPage.currentPage"
                    @update:current-page="pendingPage.currentPage = $event" :page-size="pendingPage.pageSize"
                    @update:page-size="pendingPage.pageSize = $event" :page-sizes="[10, 20, 30, 40]"
                    layout="total, sizes, prev, pager, next, jumper" :total="pendingPage.total"
                    @size-change="handlePendingSizeChange" @current-change="handlePendingCurrentChange" />
            </div>
        </el-card>

        <!-- 已提交未审批任务列表 -->
        <el-card class="box-card" shadow="never" style="margin-top: 20px;">
            <template #header>
                <div class="card-header">
                    <span>已提交未审批任务列表</span>
                </div>
            </template>
            <el-table :data="submittedTasks" style="width: 100%">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="customerName" label="客户姓名" />
                <el-table-column prop="phoneNumber" label="手机号码" />
                <el-table-column prop="channelName" label="渠道名称" />
                <el-table-column prop="activityName" label="活动名称" />
                <el-table-column prop="courseName" label="课程名称" />
                <el-table-column prop="contractAmount" label="合同金额" />
            </el-table>
            <div class="pagination-container">
                <el-pagination :current-page="submittedPage.currentPage"
                    @update:current-page="submittedPage.currentPage = $event" :page-size="submittedPage.pageSize"
                    @update:page-size="submittedPage.pageSize = $event" :page-sizes="[10, 20, 30, 40]"
                    layout="total, sizes, prev, pager, next, jumper" :total="submittedPage.total"
                    @size-change="handleSubmittedSizeChange" @current-change="handleSubmittedCurrentChange" />
            </div>
        </el-card>

        <!-- 审批完成任务列表 -->
        <el-card class="box-card" shadow="never" style="margin-top: 20px;">
            <template #header>
                <div class="card-header">
                    <span>审批完成任务列表</span>
                </div>
            </template>
            <el-table :data="approvedTasks" style="width: 100%">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="customerName" label="客户姓名" />
                <el-table-column prop="phoneNumber" label="手机号码" />
                <el-table-column prop="channelName" label="渠道名称" />
                <el-table-column prop="activityName" label="活动名称" />
                <el-table-column prop="courseName" label="课程名称" />
                <el-table-column prop="contractAmount" label="合同金额" />
                <el-table-column prop="remark" label="备注信息" />
                <el-table-column label="操作" width="180">
                    <template #default>
                        <el-button type="text" icon="View">查看</el-button>
                        <el-button type="text" icon="Document">预览</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination :current-page="approvedPage.currentPage"
                    @update:current-page="approvedPage.currentPage = $event" :page-size="approvedPage.pageSize"
                    @update:page-size="approvedPage.pageSize = $event" :page-sizes="[10, 20, 30, 40]"
                    layout="total, sizes, prev, pager, next, jumper" :total="approvedPage.total"
                    @size-change="handleApprovedSizeChange" @current-change="handleApprovedCurrentChange" />
            </div>
        </el-card>

        <!-- 添加合同弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" :close-on-click-modal="false">
            <el-form :model="formData" ref="formRef" :rules="formRules" label-width="90px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="手机号码" prop="phone">
                            <el-input v-model="formData.phone" placeholder="请输入手机号码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户姓名" prop="name">
                            <el-input v-model="formData.name" placeholder="请输入客户姓名" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="渠道来源" prop="channelId">
                            <el-select v-model="formData.channelId" placeholder="渠道来源" style="width: 100%;" disabled>
                                <el-option v-for="item in channelList" :key="item.channelId" :label="item.channelName"
                                    :value="item.channelId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="活动信息" prop="activityInfo">
                            <el-select v-model="formData.activityName" placeholder="活动信息" style="width: 100%;" disabled>
                                <!-- 假设活动信息选项 -->
                                <el-option label="活动A" value="activityA"></el-option>
                                <el-option label="活动B" value="activityB"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="课程分类" prop="courseId">
                            <el-select v-model="formData.courseId" placeholder="课程分类" style="width: 100%;" disabled>
                                <!-- 假设课程分类选项 -->
                                <el-option label="编程" value="programming"></el-option>
                                <el-option label="设计" value="design"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="购买课程" prop="courseName">
                            <el-select v-model="formData.courseName" placeholder="请选择" style="width: 100%;" disabled>
                                <!-- 假设购买课程选项 -->
                                <el-option label="Vue3" value="vue3"></el-option>
                                <el-option label="Element Plus" value="elementplus"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="审批部门" required>
                            <el-tree-select v-model="formData.departmentId" :data="deptList" placeholder="请选择归属部门"
                                style="width: 100%" node-key="id" :props="{ label: 'label', children: 'children' }"
                                check-strictly :render-after-expand="false" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="审批人" required>
                            <el-select v-model="formData.nickName" placeholder="请选择用户" style="width: 100%">
                                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName"
                                    :value="item.userId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="合同价格" prop="contractPrice">
                            <el-input-number v-model="formData.contractPrice" :min="0" controls-position="both"
                                style="width: 100%;" :step="100" :precision="2" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="合同原件" prop="contractOriginal">
                            <el-upload class="upload-demo" action="#" :auto-upload="false" :show-file-list="false"
                                :limit="1" accept=".pdf,.doc,.docx,.jpg,.png">
                                <el-button type="primary">选择合同原件</el-button>
                            </el-upload>
                            <div class="el-upload__tip">合同原件大小不能超过 5MB.</div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 合同详情弹窗 -->
        <el-dialog v-model="detailDialogVisible" title="合同详情" width="700px">
            <div style="display: flex; justify-content: space-between;">
                <div>
                    <p><b>合同编号</b><br /><i>{{ detailData.contractId }}</i></p>
                    <p><b>课程分类</b><br /><i>{{courseList.find(item => item.dictValue == detailData.courseId)?.dictLabel
                        || ''
                    }}</i></p>
                    <p><b>活动名称</b><br /><i>{{ detailData.activityName }}</i></p>
                    <p><b>课程价格</b><br /><i>{{ detailData.coursePrice }}</i></p>
                </div>
                <div>
                    <p><b>客户手机号</b><br /><i>{{ detailData.phone }}</i></p>
                    <p><b>课程名称</b><br /><i>{{ detailData.courseName }}</i></p>
                    <p><b>合同状态</b><br /><i>{{contractList.find(item => item.dictValue == detailData.status)?.dictLabel
                        || ''
                    }}</i></p>
                    <p><b>折扣类型</b><br /><i>{{activityList.find(item => item.dictValue ==
                        detailData.discountType)?.dictLabel ||
                        '' }}</i></p>
                </div>
                <div>
                    <p><b>客户姓名</b><br /><i>{{ detailData.name }}</i></p>
                    <p><b>渠道名称</b><br /><i>{{ detailData.channelName }}</i></p>
                    <p><b>合同金额</b><br /><i>{{ detailData.contractPrice }}</i></p>
                    <p><b>合同审批人</b><br /><i>{{ detailData.approveUserName }}</i></p>
                </div>
            </div>
            <template #footer>
                <el-button @click="detailDialogVisible = false">确定</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { getPaddingData, getCustomerData, contractView, activity_type, course_type, contract_type, Business_channels } from '@/api/contract/contract'
import { getDeptTree, getUsersData } from '@/api/clue/clue'
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Refresh,
    Plus,
    Download,
} from '@element-plus/icons-vue'
import * as XLSX from 'xlsx';
// 待处理任务列表数据和分页
const pendingTasks = ref([
    {
        customerName: '小',
        phoneNumber: '11111111111',
        channelName: '小程序推广',
        activityName: '1212',
        courseName: '999',
        contractAmount: '200',
    },
]);
const pendingPage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 1,
});
async function getPendingData() {
    const res = await getPaddingData()
    console.log(res.rows)
    pendingTasks.value = res.rows
    pendingPage.value.total = res.total
}
getPendingData()
const handlePendingSizeChange = (val) => {
    pendingPage.value.pageSize = val;
    // 重新获取数据
};
const handlePendingCurrentChange = (val) => {
    pendingPage.value.currentPage = val;
    // 重新获取数据
};

// 已提交未审批任务列表数据和分页

const submittedTasks = ref([]);
const submittedPage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
});
const handleSubmittedSizeChange = (val) => {
    submittedPage.value.pageSize = val;
    // 重新获取数据
};
const handleSubmittedCurrentChange = (val) => {
    submittedPage.value.currentPage = val;
    // 重新获取数据
};

// 审批完成任务列表数据和分页
const approvedTasks = ref([]);
const approvedPage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
});
const handleApprovedSizeChange = (val) => {
    approvedPage.value.pageSize = val;
    // 重新获取数据
};
const handleApprovedCurrentChange = (val) => {
    approvedPage.value.currentPage = val;
    // 重新获取数据
};

// 添加合同弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加合同');
const formRef = ref(null); // 表单引用
const formData = ref({
    phone: '',
    name: '',
    channelId: '',
    channelName: '',
    activityId: '',
    activityName: '',
    courseId: '',
    courseName: '',
    departmentId: '',
    nickName: '',
    contractPrice: 0,
    contractOriginal: null,
});
const formRules = ref({
    phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
    name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
    contractPrice: [{ required: true, message: '请输入合同价格', trigger: 'blur' }],
});
const deptList = ref([]);
const channelList = ref([]);
const handleAdd = () => {
    dialogVisible.value = true;
    // 每次打开弹窗时重置表单
    if (formRef.value) {
        formRef.value.resetFields();
    }
    getDeptTree().then((res) => {
        deptList.value = res.data
    })
    Business_channels().then((res) => {
        channelList.value = res.data
    })
};
const userList = ref([]);
function getCustomer(data) {
    getCustomerData(data).then((res) => {
        console.log(res)
        formData.value.name = res.data.name
        formData.value.channelId = res.data.channelId
        formData.value.activityId = res.data.activityId
        formData.value.courseId = res.data.courseId
        formData.value.activityName = res.data.activityName
    })
}
watch(() => formData.value.departmentId, (val) => {
    if (val) {
        console.log(val)
        getUsersData(val).then((res) => {
            console.log(res)
            userList.value = res.data
        })
    } else {
        userList.value = []
        formData.nickName = ''
    }
})
watch(() => formData.value.phone, (val) => {
    if (/^\d{11}$/.test(val)) {
        getCustomer(val)
    }
})
const submitForm = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            console.log('提交表单', formData.value);
            dialogVisible.value = false;
            // 这里可以添加提交表单的逻辑，例如调用 API
        } else {
            console.log('表单验证失败');
            return false;
        }
    });
};

const selectedPendingRows = ref([]); // 存储选中的行
const handlePendingSelectionChange = (selection) => {
    selectedPendingRows.value = selection;
};

const detailDialogVisible = ref(false);
const detailData = ref({});
const activityList = ref([]);
const courseList = ref([]);
const contractList = ref([]);
function handleView(row) {
    console.log(row)
    activity_type().then((res) => {
        console.log(res)
        activityList.value = res.data
    })
    course_type().then((res) => {
        console.log(res)
        courseList.value = res.data
    })
    contract_type().then((res) => {
        console.log(res)
        contractList.value = res.data
    })
    contractView(row.contractId).then((res) => {
        console.log(res)
        detailData.value = { ...res.data };
        console.log(detailData.value)
    })
    detailDialogVisible.value = true;
}

function handleExport() {
    // 表头
    const header = [
        '课程编号', '课程类型', '课程名称', '课程价格', '适用人群', '课程简介', '创建时间'
    ];
    // 数据
    const data = pendingTasks.value.map(item => [
        item.contractId,         // 课程编号
        item.courseCategory,   // 课程类型
        item.courseName,       // 课程名称
        item.contractPrice,      // 课程价格
        item.suitableCrowd,    // 适用人群
        item.courseIntro,      // 课程简介
        item.createTime        // 创建时间
    ]);
    // 合并表头和数据
    const wsData = [header, ...data];
    // 创建工作表
    const ws = XLSX.utils.aoa_to_sheet(wsData);
    // 创建工作簿
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '课程列表');
    // 导出
    XLSX.writeFile(wb, '课程列表.xlsx');
}

</script>

<style lang="scss" scoped>
.app-container {
    padding: 20px;
}

.box-card {
    margin-bottom: 20px;
}

.header-buttons {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    position: relative;

    .right-search {
        position: absolute;
        right: 0;
        display: flex;
        align-items: center;
    }
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    font-weight: bold;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.no-border-card {
    border: none;

    .el-card__body {
        padding: 0px !important;
        /* 移除el-card__body的默认padding */
    }
}
</style>